package com.binguo.service;

import com.alibaba.fastjson.JSONObject;
import com.binguo.common.alipay.util.PriceUtil;
import com.binguo.helper.BarcodeUtil;
import com.binguo.model.mapper.SideBoardCellDetailMapper;
import com.binguo.model.mapper.SideBoardCellsMapper;
import com.binguo.model.model.*;
import com.binguo.model.repository.BinguoOrderRepository;
import com.binguo.model.repository.OrderItemRepository;
import com.binguo.model.repository.QucanguiYilingOrderRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author yuritian
 * @Title: QrCodePayQCGService
 * @ProjectName binguoDevelop
 * @Description: TODO
 * @date 2020-02-0917:49
 */
@Service
public class QrCodePayQCGService {
    private static Logger logger = LoggerFactory.getLogger(QrCodePayQCGService.class);


    @Autowired
    AliServerPayService aliServerPayService;

    @Autowired
    QucanguiYilingOrderRepository qucanguiYilingOrderRepository;

    @Autowired
    ShopService shopService;

    @Autowired
    OrderService orderService;

    @Autowired
    BinguoOrderRepository binguoOrderRepository;


    public static void main(String[] args) {
        QrCodePayQCGService service = new QrCodePayQCGService();
        String qrCode = service.createQrCodePayQCG("YunPengTest5",1L,23,1);
        System.out.println(qrCode);
    }

    public String createQrCodePayQCG(String orderNo,Long realFee,Integer shopId,Integer payType) {

        Shop shop = shopService.findShopById(shopId);
        QucanguiYilingOrder order = new QucanguiYilingOrder();
        Boolean updateType = false;
        order.setOrderno(orderNo);
        order.setShopId(shopId);

        Condition condition = new Condition(QucanguiYilingOrder.class);
        condition.or().andEqualTo("orderno",orderNo);
        List<QucanguiYilingOrder> orderList = qucanguiYilingOrderRepository.findByCondition(condition);
        if (orderList != null && orderList.size()>0){
            order = orderList.get(0);
            order.setUpdateTime(new Date());
            updateType = true;
        }else {
            order.setCreateTime(new Date());
        }

        String qrCode = null;
        if (payType.equals(1)) {
            if (order.getWxQrcode() == null) {
                JSONObject wxQrCodeObject = aliServerPayService.qrCodePay("Z" + orderNo, PriceUtil.changeF2Y(realFee), null, shop.getSubAppid(), "1", shop.getAliMchId());
                qrCode = wxQrCodeObject.getString("qrCode");
                order.setUpdateTime(new Date());
                order.setWxQrcode(qrCode);
                order.setWxTracenum(wxQrCodeObject.getString("traceNum"));
                System.out.println("wxQrCode:   " + qrCode);
            }else {
                qrCode = order.getWxQrcode();
            }
        }else if (payType.equals(2)){
            if (order.getAliQrcode() == null) {
                JSONObject aliQrCodeObject = aliServerPayService.qrCodePay("SZ" + orderNo, PriceUtil.changeF2Y(realFee), null, shop.getSubAppid(), "2", shop.getAliMchId());
                qrCode = aliQrCodeObject.getString("qrCode");
                order.setUpdateTime(new Date());
                order.setAliQrcode(qrCode);
                order.setAliTracenum(aliQrCodeObject.getString("traceNum"));
                System.out.println("aliQrCode:   " + qrCode);
            }else {
                qrCode = order.getAliQrcode();
            }
        }
        if (updateType){
            qucanguiYilingOrderRepository.update(order);
        }else {
            qucanguiYilingOrderRepository.save(order);
        }
        String imgBase64 = BarcodeUtil.generateFile7(qrCode);

        return imgBase64;
    }

    public JSONObject queryPayResult(String orderNo){
        JSONObject queryResult = new JSONObject();
        QucanguiYilingOrder order;
        Condition condition = new Condition(QucanguiYilingOrder.class);
        condition.or().andEqualTo("orderno",orderNo);
        List<QucanguiYilingOrder> orderList = qucanguiYilingOrderRepository.findByCondition(condition);
        if (orderList != null && orderList.size()>0){
            order = orderList.get(0);
        }else {
           queryResult.put("code",2);
           queryResult.put("msg","该订单号未发起支付请求");
           logger.error(orderNo + ":  该订单号未发起支付请求");
           return queryResult;
        }
        Shop shop = shopService.findShopById(order.getShopId());
        if (order.getAliQrcode() != null){
            String code = aliServerPayService.doQuery("SZ"+orderNo,order.getAliTracenum(),shop.getSubAppid(),shop.getAliMchId());
            if(code.equals("PAYING")){
                logger.info("SZ"+orderNo+":  正在支付");
            }else if(code.equals("SUCCESS")){
                Optional<BinguoOrder> orderOptional = orderService.findByOrderNo("SZ" + orderNo);
                if (!orderOptional.isPresent()) {
                    orderOptional = orderService.findByOrderNo(orderNo);
                    if (orderOptional.isPresent()) {
                        BinguoOrder binguoOrder = orderOptional.get();
                        binguoOrder.setPaystatus(new Byte("1"));
                        binguoOrder.setSource(new Byte("5"));
                        binguoOrderRepository.update(binguoOrder);
                    }
                }
                queryResult.put("code",1);
                queryResult.put("msg","该订单号成功支付");
                return queryResult;
            }else {
                logger.error("SZ"+orderNo+":  异常订单");
            }
        }
        if (order.getWxQrcode() != null){
            String code = aliServerPayService.doQuery("Z"+orderNo,order.getWxTracenum(),shop.getSubAppid(),shop.getAliMchId());
            if(code.equals("PAYING")){
                logger.info("Z"+orderNo+":  正在支付");
            }else if(code.equals("SUCCESS")){
                Optional<BinguoOrder> orderOptional = orderService.findByOrderNo("Z" + orderNo);
                if (!orderOptional.isPresent()) {
                    orderOptional = orderService.findByOrderNo(orderNo);
                    if (orderOptional.isPresent()) {
                        BinguoOrder binguoOrder = orderOptional.get();
                        binguoOrder.setPaystatus(new Byte("1"));
                        binguoOrder.setSource(new Byte("6"));
                        binguoOrderRepository.update(binguoOrder);
                    }
                }
                queryResult.put("code",1);
                queryResult.put("msg","该订单号成功支付");
                return queryResult;
            }else {
                logger.error("Z"+orderNo+":  异常订单");
            }
        }
        queryResult.put("code",3);
        queryResult.put("msg","该订单号未完成支付");
        return queryResult;

    }

}
